// 复制文本
export function copyText(text: string, config?: { message?: string }) {
  const { message = '复制成功' } = config || {}
  const textDom = document.createElement('input')
  textDom.readOnly = true
  textDom.value = text
  document.body.appendChild(textDom)
  textDom.select()
  textDom.setSelectionRange(0, textDom.value.length)
  const result = document.execCommand('Copy')
  if (result) {
    Message.success(message)
  }
  document.body.removeChild(textDom)
}

/**
 * 动态引入js文件
 * @param src 链接
 * @param callback 状态变化的回调
 * @returns
 */
export const loadScript = (src: string) => {
  const head = document.getElementsByTagName('head')[0]
  const script: any = document.createElement('script')
  script.type = 'text/javascript'
  script.src = src
  return new Promise((ok) => {
    script.onload = script.onreadystatechange = function () {
      if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        ok('')
        script.onload = script.onreadystatechange = null
      }
    }
    head.appendChild(script)
  })
}

export const loadScriptList = async (urlList: Array<string>) => {
  await Promise.all(urlList.map(loadScript))
  return true
}

/**
 * 等待一定时间后继续执行（async中
 * @param time 等待时间
 * @returns a Promise
 */
export const timeSleep = (time: number) =>
  new Promise((success) => {
    setTimeout(success, time)
  })
